<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>题目1</title>

    <style>
        .wrapper {
            width: 500px;
        }

        input {
            width: 100%;
        }

        #rel {
            width: 100%;
        }

        #rel>div {
            width: 100%;
            line-height: 1.5;
            border: 1px solid black;
        }

        #rel>div:hover {
            background: cadetblue;
        }
    </style>
</head>

<body>
    <!-- 写代码用原生JS实现一个类似百度搜索框的自动完成控件，
        比如候选结果集arr=['aaa', 'abc', 'acc', 'dda',…]; 用户输入'a',下拉列表会出现以字母a开头的项'aaa', 'abc', 'acc'。要求，鼠标或键盘可以选中候选结果到输入框
     -->

    <div class="wrapper">
        <input id="input" type="text" placeholder="请输入">
        <div id="rel">

        </div>
    </div>

</body>
<script>
    const sourceArr = ['aaa', 'abc', 'acc', 'dda']
    const inputEl = document.getElementById('input')
    const relEl = document.getElementById('rel')
    const optEl = document.getElementsByClassName('item')
    let matchedData = []
    inputEl.addEventListener('input', (e => {
        const value = e.target.value
        const valueLength = value.length
        let tmpStr = ''
        sourceArr.forEach((item, idx) => {
            if (value === item.substring(0, valueLength)) {
                matchedData.push(item)
                tmpStr +=
                    `<div class='item' onclick="onSelect(${matchedData.length-1})">${item}</div>`
            }
        })
        relEl.innerHTML = tmpStr
    }))

    function onSelect(idx) {
        console.log('matchedData---->>', matchedData, idx)
        inputEl.value = matchedData[idx]
        relEl.innerHTML = ''
        matchedData = []
    }
</script>

</html>